package com.logistics.utils.webservice.callback;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.logistics.utils.configure.Configure;
import com.logistics.utils.tool.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.namespace.QName;

@Component
public class WebServiceCallback {

    @Autowired
    private Configure configure;

    /**
     * 有参数调用
     * @param methodName
     * @param params
     * @return
     * @throws Exception
     */
    public String send(String methodName, String... params) throws Exception {
        JaxWsDynamicClientFactory jaxWsDynamicClientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = jaxWsDynamicClientFactory.createClient(configure.getWebService().getRemoteWsdlAddress());
        QName qName = new QName(configure.getWebService().getRemoteNamespaceUrl(), methodName);
        Object[] result = client.invoke(qName, StringUtils.isNotNull(params) ? params : null);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(result[0]);
    }

    /**
     * 无参数调用
     * @param methodName
     * @return
     * @throws Exception
     */
    public String send(String methodName) throws Exception {
        return send(methodName, null);
    }
}
